<template>
	<view v-if="item" class="wrap-item">
		<view class="title-bg">
			<view class="must" v-if="item.hasOwnProperty('require') && item.require">
				*
			</view>
			<view class="title">
				{{ item.title }}
			</view>
		</view>

		<view class="wrap-list m-t-30">
			<block v-for="(imgItem, imgIdx) in value === '' ? [] : value.split(',')" :key="imgIdx">
				<view class="photo-item">
					<image class="photo-img" mode="aspectFill" :src="$wanlshop.oss(imgItem)" />

					<image class="photo-delete" :src="$staticImagePath('store/delete.png')"
						@click="onDeleteImage(imgIdx)" />
				</view>
			</block>
			<image class="photo-item" v-if="isShow()" :src="$staticImagePath('store/upload.png')"
				@click="onChooseImage" />
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			/**
			 * 输入框的值
			 */
			value: {
				type: String,
				default: "",
			},
			/**
			 * 数据
			 */
			item: {
				type: Object,
				default: null,
			},
		},
		data() {
			return {
				imageList: [],
			};
		},
		computed: {
			maxNumber() {
				var maxNum = 9;
				if (this.item && this.item.hasOwnProperty("maxNum")) {
					maxNum = this.item.maxNum;
				}
				return maxNum;
			}
		},
		methods: {
			/**
			 * 是否显示
			 */
			isShow() {
				if (this.value === "" || this.value.split(",").length < this.maxNumber) {
					return true;
				} else {
					return false;
				}
			},
			/**
			 * 选择图片
			 */
			onChooseImage() {
				let array = this.$filters.getImageArray(this.value);
				this.$filters.onChooseImage(this.maxNumber - array.length, (list) => {
					this.onUploadImage(0, list);
				});
			},
			/**
			 * 上传图片
			 */
			onUploadImage(index, list) {
				this.$commonNetwork.onUploadFile(list[index], (res) => {
					this.imageList.push(res.url);

					if (index < list.length - 1) {
						this.onUploadImage(index + 1, list);
					} else {
						let array = this.$filters.getImageArray(this.value);
						array = array.concat(this.imageList);
						this.$emit("input", array.join(","));
						this.imageList = [];
					}
				});
			},
			/**
			 * 删除图片
			 */
			onDeleteImage(index) {
				let array = this.$filters.getImageArray(this.value);
				array.splice(index, 1);
				this.$emit("input", array.join(","));
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../css/form.css";
</style>